/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pkgUtil.pkgFrameworkClipboard.pkgAdapter;

import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.util.StringTokenizer;
import javax.swing.JTable;
import pkgUtil.pkgFrameworkClipboard.IAdapterClipboard;
import pkgUtil.pkgFrameworkClipboard.UtilClipboard;

/**
 *
 * @author DICSYS
 */
public class AdapterForJTable implements IAdapterClipboard {

    private final String SEPARATOR_COLUMN = "\t";
    private final String SEPARATOR_ROW = "\n";
    private JTable tblComponent;

    /**
     * The Excel Adapter is constructed with a JTable on which it enables
     * Copy-Paste and acts as a Clipboard listener.
     */
    public AdapterForJTable() {
    }

    /**
     * Registra el Listener para Copy y Paste para el JTable
     */
    public void registerListener(JTable tblComponent) {
        this.tblComponent = tblComponent;
        UtilClipboard.registerListenerForCopyPaste(tblComponent, this);
    }

    /**
     * This method is activated on the Keystrokes we are listening to in this
     * implementation. Here it listens for Copy and Paste ActionCommands.
     * Selections comprising non-adjacent cells result in invalid selection and
     * then copy action cannot be performed. Paste is done by aligning the upper
     * left corner of the selection with the 1st element in the current
     * selection of the JTable.
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().compareTo(UtilClipboard.ID_COPY) == 0) {
            copyToClipboard();
        }
        if (e.getActionCommand().compareTo(UtilClipboard.ID_PASTE) == 0) {
            pasteFromClipboard();
        }
    }

    @Override
    public void copyToClipboard() {
        StringBuilder sbf = new StringBuilder();

        int numcols = tblComponent.getSelectedColumnCount();
        int numrows = tblComponent.getSelectedRowCount();
        int[] rowsselected = tblComponent.getSelectedRows();
        int[] colsselected = tblComponent.getSelectedColumns();
        //Se chequea que se hayan seleccionado celdas contiguas
        if (!((numrows - 1 == rowsselected[rowsselected.length - 1] - rowsselected[0]
                && numrows == rowsselected.length)
                && (numcols - 1 == colsselected[colsselected.length - 1] - colsselected[0]
                && numcols == colsselected.length))) {
            return;
        }
        for (int i = 0; i < numrows; i++) {
            for (int j = 0; j < numcols; j++) {
                sbf.append(tblComponent.getModel().getValueAt(rowsselected[i], colsselected[j]));
                if (j < numcols - 1) {
                    sbf.append(SEPARATOR_COLUMN);
                }
            }
            sbf.append(SEPARATOR_ROW);
        }
        
        StringSelection stsel = new StringSelection(sbf.toString());
        UtilClipboard.setContentsClipboard(stsel);
    }

    @Override
    public void pasteFromClipboard() {
        int startRow = (tblComponent.getSelectedRows())[0];
        int startCol = (tblComponent.getSelectedColumns())[0];
        String trstring;
        try {
            trstring = UtilClipboard.getContentsFromClipboard(this);
        } catch (Exception ex) {
            ex.printStackTrace();
            return;
        }

        String rowstring, value;
        StringTokenizer st1 = new StringTokenizer(trstring, SEPARATOR_ROW);
        for (int i = 0; st1.hasMoreTokens(); i++) {
            rowstring = st1.nextToken();
            StringTokenizer st2 = new StringTokenizer(rowstring, SEPARATOR_COLUMN);
            for (int j = 0; st2.hasMoreTokens(); j++) {
                value = (String) st2.nextToken();
                if (startRow + i < tblComponent.getModel().getRowCount()
                        && startCol + j < tblComponent.getModel().getColumnCount()) {
                    int rowIndex = startRow + i;
                    int colIndex = startCol + j;
                    if (tblComponent.getModel().isCellEditable(rowIndex, colIndex)) {
                        tblComponent.getModel().setValueAt(value, rowIndex, colIndex);
                    }
                }
            }
        }

    }

    /**
     * @return the tblComponent
     */
    public JTable getTblComponent() {
        return tblComponent;
    }

    /**
     * @param tblComponent the tblComponent to set
     */
    public void setTblComponent(JTable tblComponent) {
        this.tblComponent = tblComponent;
    }
}
